# 创建窗口
# 开户窗口 主窗口设置都要在这个上面设置
# 设置窗口
import time
import json
import tkinter as tk
from tkinter import messagebox
from tkinter.ttk import Combobox
from tkinter import END
from tkinter import filedialog
import pandas as pd

file_path = None


# 设置窗品关闭时执行的函数
def confimClose():
    print("确认要关吗？")
    # 销毁窗口、组件、子窗口
    w1.destroy()


def handleBtn1():
    print("确认")
    print('input:' + user_name.get())
    print('select:' + select.get())
    print('radio:' + radio.get())
    print(f'check:{check1.get()}')
    # messagebox.showinfo('提示', '用户输入的值为：' + user_name.get())
    # messagebox.showerror('提示', '用户输入的值为：' + user_name.get())
    messagebox.showwarning('提示', '用户输入的值为：' + user_name.get())
    # askbox = messagebox.askquestion('提示',"确认要执行吗？")#Yes|no
    askbox = messagebox.askokcancel('提示', "确认要执行吗？")  # True|False
    print(askbox)


# 解析json
def handelJson():
    try:
        with open('down.json', encoding='utf-8') as f:
            config = json.load(f)
            print(f"成功加载配置：{config}")
            for item in config:
                print(f"{item['name']},{item['age']}")
    except FileNotFoundError:
        print("错误：文件不存在")
    except json.JSONDecodeError:
        print("错误：JSON格式无效")


def handelReadExcel():
    if not file_path:
        print("未选择文件")
        return
    try:
        # 读取Excel数据
        df = pd.read_excel(file_path)
        # 遍历数据
        print(f"共{len(df)}行数据：")
        for index, row in df.iterrows():
            print(f"第{index + 1}行：{row.to_dict()}")
            listboxElm.insert(END, f"第{index + 1}行：{row.to_dict()}")  # 在行尾添加
            listboxElm.yview_moveto(1)  # 滚动到底部

    except Exception as e:
        print(f"读取失败：{str(e)}")


# 选择目录
def handelSelecDirectory():
    # w1.withdraw()
    dir = filedialog.askdirectory()
    if dir:
        print("选择的目录是：", dir)
    else:
        print("没有选择目录")


# 选择文件
def handelSelecFile():
    global file_path
    file_path = filedialog.askopenfilename(filetypes=[('excel', '*.xlsx'), ('excel', '*.xls')], title='员工花名单')
    if file_path:
        print("选择的文件是：", file_path)
    else:
        print("没有选择文件")


# 创建窗口
w1 = tk.Tk()
# 设置标题
w1.title("我是标题")
# 获取用户分辨率
maxsize = w1.maxsize()
maxwidth, maxheight = maxsize
print(maxwidth)
print(maxheight)
# 锁定窗口
w1.resizable(False, False)
# 设置窗口图标
# w1.iconbitmap('xxx.ico')
# 设置背景色
w1.configure(bg="#ccc")
# 设置透明度
w1.attributes('-alpha', 1)
# 设置窗口置顶
w1.attributes('-topmost', False)

w1.protocol('WM_DELETE_WINDOW', confimClose)
# 销毁窗口、组件、子窗口
# w1.destroy()

# 设置窗口大小 字母x
# 设置窗口位置
# 例子：长x宽+距屏左侧+距屏顶
w1.geometry('400x500+600+200')

# 组件----
label1 = tk.Label(w1, text='测试', font=('黑体', 14), fg='#fff', bg="#ccc")

# 组件布局 默认布局或填充pack、自定义布局place(x,y)相对于当前窗口、网络布局grid(row=行,column=列)

label1 = tk.Label(w1, text='测试', font=('黑体', 14), fg='#fff', bg="#ccc")
label1.pack()
tk.Label(w1, text='测试', font=('黑体', 14), fg='#fff', bg="#ccc").pack()

# Entry组件
user_name = tk.StringVar()
user_name.set("提示语")  # 提示文本
tk.Entry(w1, textvariable=user_name, width=15, font=('黑体', 14)).pack()

# 下拉组件
select = tk.StringVar()
selectElm1 = Combobox(w1, name="测试", textvariable=select, values=["哈哈", "哈2"])
selectElm1.pack()
# 设置默认选中
# select.set("哈2") # 方式一
selectElm1.current(0)  # 方式二
print(select)
# 单选
radio = tk.StringVar(value="女")  # 并设置默认值
tk.Radiobutton(w1, name="单选1", variable=radio, text="男", value="男").pack()
tk.Radiobutton(w1, name="单选2", variable=radio, text="女", value="女").pack()
# 多选
check1 = tk.IntVar()
checkElm1 = tk.Checkbutton(w1, text="跑步", variable=check1, onvalue=1, offvalue=0)
checkElm1.pack()
checkElm1.setvar()

# 列表框
listboxElm = tk.Listbox(w1, width=60, height=4)
listboxElm.pack()
listboxElm.insert(END, '123')  # 在行尾添加
i = 0
while i < 100:
    listboxElm.insert(END, f'123---{i}')  # 在行尾添加
    i = i + 1
listboxElm.yview_moveto(1)  # 滚动到底部

buttonFrame = tk.Frame(w1,
                       #width=350,
                       #height=250,
                       bg="#F0F8FF",  # 背景色
                       bd=3,  # 边框宽度
                       relief=tk.GROOVE,  # 凹槽边框
                       padx=20,  # 水平内边距
                       pady=15,  # 垂直内边距
                       highlightthickness=2,  # 焦点边框宽度
                       highlightcolor="red"  # 焦点边框颜色
                       )
# 按钮
tk.Button(buttonFrame, text="确定", font=('黑体', 14), width=14, command=handleBtn1).grid(row=1, column=1)
tk.Button(buttonFrame, text="设置输出目录", font=('黑体', 14), width=14, command=handelSelecDirectory).grid(row=1,
                                                                                                            column=2)
tk.Button(buttonFrame, text="选择文件", font=('黑体', 14), width=14, command=handelSelecFile).grid(row=2, column=1)
tk.Button(buttonFrame, text="遍历文件", font=('黑体', 14), width=14, command=handelReadExcel).grid(row=2, column=2)
tk.Button(buttonFrame, text="解析json", font=('黑体', 14), width=14, command=handelJson).grid(row=3, column=1)
buttonFrame.pack()
# 开启窗口
w1.mainloop()
